package com.net4.contact;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class AndroidContact extends Activity {
    /** Called when the activity is first created. */
	
	private static final String GET_CONTACT_URL = "http://mobilecontactonline.appspot.com/info/contact/get";
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        TextView text = (TextView)this.findViewById(R.id.text1);
        HttpClient httpClient = new DefaultHttpClient();
    	HttpPost post = new HttpPost(GET_CONTACT_URL);
    	List<NameValuePair> params = new ArrayList<NameValuePair>();
    	params.add(new BasicNameValuePair("u", "mk2"));
    	try {
			post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
        try {
        	HttpResponse response = httpClient.execute(post);
        	String c = EntityUtils.toString(response.getEntity());
        	JSONArray json = new JSONArray(c);
        	
        	if(response.getStatusLine().getStatusCode() == 200) {
    			text.setText(c + " username:" + json.getJSONObject(0).getString("name"));
        	} else {
    			text.setText("Server Error: " + c);
        	}
        	
		} catch (Exception e) {
			// TODO Auto-generated catch block
			text.setText("URL Error " + e.toString());
			e.printStackTrace();
		}
    }
}